import { FC } from 'react';
import styles from './LayerItem.module.scss';
import { ComponentInfo } from '@/components/editor';
import classNames from 'classnames';
import { useEditorStore } from '@/store/editor';
import { Button, Input, message, Space } from 'antd';
import createStore from '@/hooks/state-link';
import { EyeInvisibleOutlined, LockOutlined } from '@ant-design/icons';

export const useChangindId = createStore('333');

interface LayerItemProps {
  info: ComponentInfo;
}

const LayerItem: FC<LayerItemProps> = (props) => {
  const {
    componentList,
    select,
    selectedId,
    updateSelected,
    showHidden,
    toggleLock,
  } = useEditorStore();
  const [changingId, setChangingId] = useChangindId();
  const { info } = props;
  const { fe_id, title, isHidden, isLocked } = info;

  const clas = classNames({
    [styles.title]: true,
    [styles.selected]: selectedId === fe_id,
  });

  function click(id: string = '') {
    const target = componentList.find((item) => item.fe_id === id);
    if (target?.isHidden) {
      message.info('无法选中隐藏图层');
      return;
    }
    if (id !== selectedId) {
      select(id);
      setChangingId('');
    } else {
      setChangingId(id);
    }
  }

  function onChange(e: any) {
    updateSelected({ title: e.target.value });
  }

  function onBlur() {
    setChangingId('');
  }

  function show(e: any) {
    e.stopPropagation();
    showHidden(fe_id);
  }

  function lock(e: any) {
    e.stopPropagation();
    toggleLock(fe_id);
  }

  const left =
    changingId === fe_id ? (
      <Input
        value={title}
        onChange={onChange}
        onBlur={onBlur}
        onPressEnter={onBlur}
      />
    ) : (
      title
    );

  return (
    <div key={fe_id} className={styles.wrapper} onClick={() => click(fe_id)}>
      <div className={clas}>{left}</div>
      <div className={styles.handle}>
        <Space>
          <Button
            size="small"
            className={styles.btn}
            shape="circle"
            onClick={show}
            icon={<EyeInvisibleOutlined />}
            type={isHidden ? 'primary' : 'text'}
          />
          <Button
            size="small"
            className={styles.btn}
            shape="circle"
            onClick={lock}
            icon={<LockOutlined />}
            type={isLocked ? 'primary' : 'text'}
          />
        </Space>
      </div>
    </div>
  );
};

export default LayerItem;
